package com.toolbox.service.impl;

import com.toolbox.service.PhotoService;
import com.toolbox.utils.ImageProcessor;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import com.toolbox.utils.picturetool.ImageBgChange;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.*;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.awt.*;

@Service
public class PhotoServiceImpl implements PhotoService {

    private static final String TEMP_DIR = System.getProperty("java.io.tmpdir");

    @Override
    public InputStream changePhotoBackground(MultipartFile file, String backgroundColor) throws IOException {
        // 保存上传的照片到临时目录
        String originalFilename = file.getOriginalFilename();
        Path tempFilePath = Paths.get(TEMP_DIR, originalFilename);
        Files.write(tempFilePath, file.getBytes());

        // 使用ImageProcessor处理照片背景
        BufferedImage processedImage;
        try {
            processedImage = ImageProcessor.changeBackground(tempFilePath.toString(), backgroundColor);
        } catch (Exception e) {
            throw new IOException("照片背景处理失败: " + e.getMessage(), e);
        }

        // 保存处理后的图像
        Path processedFilePath = Paths.get(TEMP_DIR, "processed_" + originalFilename);
        String format = originalFilename.substring(originalFilename.lastIndexOf(".") + 1);
        ImageIO.write(processedImage, format, processedFilePath.toFile());

        // 返回处理后的照片输入流
        return new FileInputStream(processedFilePath.toFile());
    }

    @Override
    public InputStream changePhotoBackground2(MultipartFile file, String backgroundColor) throws IOException {
        // 保存上传的照片到临时目录
        String originalFilename = file.getOriginalFilename();
        if (originalFilename == null || !originalFilename.contains(".")) {
            throw new IllegalArgumentException("无效的文件名");
        }
        
        Path tempFilePath = Paths.get(TEMP_DIR, originalFilename);
        Files.write(tempFilePath, file.getBytes());
        
        // 根据backgroundColor参数选择对应的颜色
        Color targetColor;
        switch (backgroundColor.toLowerCase()) {
            case "white":
                targetColor = Color.WHITE;
                break;
            case "black":
                targetColor = Color.BLACK;
                break;
            case "green":
                targetColor = Color.GREEN;
                break;
            case "blue":
                targetColor = Color.BLUE;
                break;
            case "yellow":
                targetColor = Color.YELLOW;
                break;
            case "red":
                targetColor = Color.RED;
                break;
            case "transparent_black":
                targetColor = new Color(0, 0, 0, 0);
                break;
            case "transparent_white":
                targetColor = new Color(255, 255, 255, 0);
                break;
            default:
                throw new IllegalArgumentException("不支持的背景颜色: " + backgroundColor);
        }
        
        // 根据ImageBgChange.changeBgColor的实现，计算生成的输出文件路径
        String tempFilePathStr = tempFilePath.toString();
        String suffix = tempFilePathStr.substring(tempFilePathStr.lastIndexOf("."));
        String outputFilePath = tempFilePathStr.replace(suffix, "_" + targetColor.getRGB() + suffix);
        
        // 使用ImageBgChange处理照片背景（注意：该方法只有三个参数）
        try {
            ImageBgChange.changeBgColor(tempFilePathStr, targetColor, 45);
            
            // 验证文件是否存在
            if (!Files.exists(Paths.get(outputFilePath))) {
                throw new IOException("处理后的文件未生成: " + outputFilePath);
            }
        } catch (Exception e) {
            throw new IOException("照片背景处理失败: " + e.getMessage(), e);
        }
        
        // 返回处理后的照片输入流
        return new FileInputStream(outputFilePath);
    }
}